package stack;

import java.util.Stack;

public class leetcode20_2 {
    public static void main(String[] args) {
        String s = "()[]{}";
        System.out.println(isValid(s));
    }

    public static boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);  // 左括号入栈
            } else {
                if (stack.isEmpty()) return false;  // 栈为空，无法匹配

                char top = stack.pop();  // 取出栈顶元素
                if (!isMatchingPair(top, c)) {
                    return false;  // 不匹配
                }
            }
        }

        return stack.isEmpty();  // 栈为空才有效
    }

    private static boolean isMatchingPair(char left, char right) {
        return (left == '(' && right == ')') ||
                (left == '{' && right == '}') ||
                (left == '[' && right == ']');
    }
}
